var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

global.allowUrl = 'http://127.0.0.1:5500'

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json({
  // 注意: 如果post的请求体负载过大(我传base64), 可能就会出问题, 需要设置服务器接收的limit限制,尽可能调大
  // 我在前端写的页面里限制的是100MB但是我是base64的形式转化的, 会增大图片的体积约30%,所以这里设置150MB
  limit: 1024 * 1024 * 1024
}));
app.use(express.urlencoded({
  extended: false,
  limit: 1024 * 1024 * 1024
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'tmp')));


// 注意,如果有post请求跨域,则必须要在这里加app.all,否则就会出现问题,即使在router.post内部加都不行
app.all("*", function (req, res, next) {
  // 必须要加的是Access-Control-Allow-Origin和Access-Control-Allow-Headers
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // res.header("Access-Control-Allow-Methods", "*");
  // res.header("X-Powered-By",' 3.2.1')
  // res.header("Content-Type", "application/json;charset=utf-8");
  req.method === 'OPTIONS'? res.send('CURRENT SERVICES SUPPORT CROSS DOMAIN REQUESTS!') : next()
})

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
